package com.foo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;

@Singleton
@Startup
public class StartupSingleton {

	@Inject
	private FooStateless foo;
	
	@PostConstruct
	public void postConstruct() {
		deserialize( serialize( foo ) );
	}

	public byte[] serialize(Object object) {
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(out);				
			oos.writeObject(object);
			oos.flush();
			oos.close();
			return out.toByteArray();
		} catch( Exception e ) {
			throw new RuntimeException( e );
		}
	}
	
	public Object deserialize(byte[] data) {
		try {
			ByteArrayInputStream in = new ByteArrayInputStream(data);
			ObjectInputStream ois = new ObjectInputStream(in);
			return ois.readObject();
		} catch (Exception e) {
			throw new RuntimeException( e );
		}		
	}
}
